package com.xbongbong.saas.service.impl;

import com.alibaba.dingtalk.openapi.exception.OApiException;
import com.alibaba.dingtalk.openapi.helper.AuthHelper;
import com.alibaba.dingtalk.openapi.helper.Env;
import com.alibaba.dingtalk.openapi.helper.GroupRobotHelper;
import com.alibaba.dingtalk.openapi.helper.MiniMemberInfoHelper;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.TimeConstant;
import com.xbongbong.paas.domain.entity.PaasAppEntity;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.help.CreateImageHelper;
import com.xbongbong.paas.model.PaasAppModel;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.CommentUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.util.URLEncodeUtils;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.pro.bundle.dto.BundleCreateDTO;
import com.xbongbong.pro.bundle.dto.BundleGetDTO;
import com.xbongbong.pro.bundle.dto.BundleInfoSynDTO;
import com.xbongbong.pro.bundle.dto.BundleInfoUndateDTO;
import com.xbongbong.pro.bundle.dto.BundleMemberAddDTO;
import com.xbongbong.pro.bundle.dto.BundleMemberDeleteDTO;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.BundleErrorCodeEnum;
import com.xbongbong.pro.message.pojo.dto.MessageSaveAllDingRobotDataDTO;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.DingBundleEntity;
import com.xbongbong.saas.domain.entity.DingBundleRankEntity;
import com.xbongbong.saas.domain.entity.DingBundleUserEntity;
import com.xbongbong.saas.domain.entity.DingReportEntity;
import com.xbongbong.saas.domain.entity.DingRobotManageEntity;
import com.xbongbong.saas.enums.DingtalkPageUrlEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.mini.DingBundleRobotMsgKeyEnum;
import com.xbongbong.saas.enums.mini.DingBundleTypeEnum;
import com.xbongbong.saas.enums.mini.DingBundleUserOperateEnum;
import com.xbongbong.saas.enums.mini.DingRobotManagePushEnum;
import com.xbongbong.saas.model.DingBundleModel;
import com.xbongbong.saas.model.DingBundleRankModel;
import com.xbongbong.saas.model.DingBundleUserModel;
import com.xbongbong.saas.model.DingReportModel;
import com.xbongbong.saas.model.DingRobotManageModel;
import com.xbongbong.saas.service.BundleService;
import com.xbongbong.saas.toolbox.help.SortHelp;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.rangeQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * 应用模块名称<p>
 * 代码描述<p>
 * Company: 逍邦网络科技有限公司<p>
 *
 * @author chenshan
 * @version v1.0
 * @since 2020/8/21 2:51 下午
 */
@Service("bundleService")
public class BundleServiceImpl implements BundleService {
    private static final Logger LOG = LoggerFactory.getLogger(BundleServiceImpl.class);
    @Resource
    private ProBaseConfig proBaseConfig;
    @Resource
    private DingBundleModel dingBundleModel;
    @Resource
    private DingBundleUserModel dingBundleUserModel;
    @Resource
    private UserModel userModel;
    @Resource
    private AuthHelper authHelper;
    @Resource
    private MiniMemberInfoHelper miniMemberInfoHelper;
    @Resource
    private DingRobotManageModel dingRobotManageModel;
    @Resource
    private EsHelper esHelper;
    @Resource
    private DingReportModel dingReportModel;
    @Resource
    private DingBundleRankModel dingBundleRankModel;
    @Resource
    private CreateImageHelper createImageHelper;
    @Resource
    private GroupRobotHelper groupRobotHelper;
    @Resource
    private PaasAppModel paasAppModel;
    
    @Override
    public BaseVO createBundle(BundleCreateDTO bundleCreateDTO) throws XbbException {
        String corpid = bundleCreateDTO.getCorpid();
        String ownerId = bundleCreateDTO.getUserId();
        String title = bundleCreateDTO.getTitle();
        List<String> userIdIn = bundleCreateDTO.getUserList();
        StringBuilder addMembers = StringUtil.arrayBuilderAppendSuffix(new StringBuilder(),",",userIdIn);
        String openConversationId = null;
        try {
            openConversationId = miniMemberInfoHelper.createGroup(corpid,title,ownerId,addMembers.toString());
        } catch (OApiException e) {
            throw new XbbException(BundleErrorCodeEnum.API_ERROR_1010011.getCode(),String.format(BundleErrorCodeEnum.API_ERROR_1010011.getMsg(),e.getErrMsg()));
        }
        userIdIn.add(ownerId);
        List<UserEntity> userList = userModel.getByUserId(userIdIn, bundleCreateDTO.getCorpid());
        Map<String, UserEntity> userEntityMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        userList.forEach(userEntity -> {
            userEntityMap.put(userEntity.getUserId(), userEntity);
        });
        DingBundleEntity dingBundleEntity = new DingBundleEntity();
        BeanUtil.copyProperties(bundleCreateDTO, dingBundleEntity);
        UserEntity userEntity = userEntityMap.get(ownerId);
        dingBundleEntity.setAvatar(userEntity.getAvatar());
        dingBundleEntity.setName(userEntity.getName());
        dingBundleEntity.setOwnerId(ownerId);
        dingBundleEntity.setType(DingBundleTypeEnum.SALES_GROUP.getCode());
        dingBundleEntity.setOpenConversationId(openConversationId);
        dingBundleModel.insert(dingBundleEntity);
        Long bundleId = dingBundleEntity.getId();
        List<DingBundleUserEntity> list = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for ( String userId : userIdIn ) {
            UserEntity user = userEntityMap.get(userId);
            DingBundleUserEntity dingBundleUserEntity = new DingBundleUserEntity(bundleId, corpid, openConversationId, user);
            if ( Objects.equals(userId, ownerId) ) {
                dingBundleUserEntity.setIdentity(0);
            }
            list.add(dingBundleUserEntity);
        }
        if ( CollectionsUtil.isNotEmpty(list) ) {
            dingBundleUserModel.insertBatch(list);
        }
        return new BaseVO();
    }
    
    @Override
    public BaseVO updateBundleInfo(BundleInfoUndateDTO bundleInfoUndateDTO) throws XbbException {
        String corpid = bundleInfoUndateDTO.getCorpid();
        String accessToken = null;
        try {
            accessToken = authHelper.getAccessToken(corpid);
        } catch (OApiException e) {
        
        }
        
        return null;
    }
    
    @Override
    public BaseVO getBundleInfo(BundleGetDTO bundleGetDTO) throws XbbException {
        
        
        return null;
    }
    
    @Override
    public BaseVO addBundleMember(BundleMemberAddDTO bundleMemberAddDTO) throws XbbException {
        String corpid = bundleMemberAddDTO.getCorpid();
        Long dataId = bundleMemberAddDTO.getDataId();
        DingBundleEntity dingBundleEntity = dingBundleModel.getEntity(dataId, corpid);
        if ( Objects.isNull(dingBundleEntity) ) {
            throw new XbbException(BundleErrorCodeEnum.API_ERROR_1010016);
        }
        List<String> addMembers = bundleMemberAddDTO.getAddMembers();
        String openConversationId = dingBundleEntity.getOpenConversationId();
        StringBuilder addMemberBuilder = StringUtil.arrayBuilderAppendSuffix(new StringBuilder(),",",addMembers);
        try {
//            Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
//            params.put("orderByStr","identity asc");
//            params.put("bundleId",dataId);
//            params.put("corpid",corpid);
//            params.put("del",0);
//            //查询数据库中已经添加的成员实体集合
//            List<DingBundleUserEntity> userList = dingBundleUserModel.findEntitys(params);
//            //将查询到的实体集合的userId放在userIdSet集合中
//            Set<String> userIdSet = new HashSet<>();
//            for (DingBundleUserEntity dingBundleUserEntity : userList) {
//                userIdSet.add(dingBundleUserEntity.getUserId());
//            }
//            //将数据库中已经含有的想添加的用户id去除
//            addMembers.removeAll(userIdSet);
            miniMemberInfoHelper.addMember(openConversationId,addMemberBuilder.toString(),dingBundleEntity.getCorpid());
            //根据添加的成员进行添加更新
//            updateBundleUser(corpid,dingBundleEntity.getId(),dingBundleEntity.getOpenConversationId(),addMembers, null,DingBundleUserOperateEnum.ADD_MEMBER);
        } catch (Exception e) {
            LOG.error("BundleServiceimpl.removeBundleMember移除成员失败",e);
            throw new XbbException(BundleErrorCodeEnum.API_ERROR_1010013);
        }
        return new BaseVO();
    }

    @Override
    public BaseVO removeBundleMember(BundleMemberDeleteDTO bundleMemberDeleteDTO) throws XbbException {
        String corpid = bundleMemberDeleteDTO.getCorpid();
        Long dataId = bundleMemberDeleteDTO.getDataId();
        DingBundleEntity dingBundleEntity = dingBundleModel.getEntity(dataId, corpid);
        if ( Objects.isNull(dingBundleEntity) ) {
            throw new XbbException(BundleErrorCodeEnum.API_ERROR_1010016);
        }
        List<String> deleteMembers = bundleMemberDeleteDTO.getDeleteMembers();
        String openConversationId = dingBundleEntity.getOpenConversationId();
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid",corpid);
        param.put("bundleId",dataId);
        param.put("del",0);
        param.put("identityNot",0);
        param.put("userIdIn",deleteMembers);
        List<DingBundleUserEntity> dingBundleUserEntityList = dingBundleUserModel.findEntitys(param);
        List<String> deleteUserId = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<Long> deleteIdIn = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        dingBundleUserEntityList.forEach(user->{
            deleteUserId.add(user.getUserId());
            deleteIdIn.add(user.getId());
        });
        if ( CollectionsUtil.isEmpty(deleteIdIn) || CollectionsUtil.isEmpty(deleteIdIn) ) {
            return new BaseVO();
        }
        StringBuilder removeMemberBuilder = StringUtil.arrayBuilderAppendSuffix(new StringBuilder(),",",deleteUserId);
        try {
            miniMemberInfoHelper.deleteMember(openConversationId,removeMemberBuilder.toString(),dingBundleEntity.getCorpid());
//            updateBundleUser(corpid,dingBundleEntity.getId(),openConversationId,deleteUserId,deleteIdIn,DingBundleUserOperateEnum.DELETE_MEMBER);
        } catch (Exception e) {
            LOG.error("BundleServiceimpl.removeBundleMember移除成员失败",e);
            throw new XbbException(BundleErrorCodeEnum.API_ERROR_1010012);
        }
        return new BaseVO();
    }
    
    /**
     *
     * @param corpid
     * @param bundleId 系统群编号
     * @param openConversationId 第三方群编号
     * @param userIds 要操作的用户编号，比如新增成员，移除成员
     * @param operateEnum 操作类型，1:新增，2:删除
     */
    private void updateBundleUser(String corpid, Long bundleId, String openConversationId ,List<String> userIds,List<Long> dataIdIn, DingBundleUserOperateEnum operateEnum) {
        switch (operateEnum) {
            case ADD_MEMBER:
                List<UserEntity> userEntityList =  userModel.getByUserId(userIds,corpid);
                List<DingBundleUserEntity> dingBundleUserList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                Map<String, UserEntity> userEntityMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                userEntityList.forEach(userEntity -> {
                    userEntityMap.put(userEntity.getUserId(), userEntity);
                });
                for ( String userId : userIds ) {
                    UserEntity userEntity = userEntityMap.get(userId);
                    if ( Objects.isNull(userEntity) ) {
                        continue;
                    }
                    DingBundleUserEntity dingBundleUserEntity = new DingBundleUserEntity(bundleId,corpid,openConversationId,userEntity);
                    dingBundleUserList.add(dingBundleUserEntity);
                }
                if ( CollectionsUtil.isNotEmpty(dingBundleUserList) ) {
                    dingBundleUserModel.insertBatch(dingBundleUserList);
                }
                break;
            case DELETE_MEMBER:
                dingBundleUserModel.deleteByIds(dataIdIn,corpid);
                break;
            default:
                break;
        }


    }
    
    @Override
    public BaseVO synBundleInfo(BundleInfoSynDTO bundleInfoSynDTO) throws XbbException {
        String corpid = bundleInfoSynDTO.getCorpid();
        String accessToken = null;
        try {
            accessToken = authHelper.getAccessToken(corpid);
        } catch (OApiException e) {
        
        }
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("status",1);
        param.put("del", 0);
        param.put("type", DingBundleTypeEnum.SALES_GROUP.getCode());
        List<DingBundleEntity> dingBundleEntityList = dingBundleModel.findEntitys(param);
    
        for ( DingBundleEntity dingBundleEntity : dingBundleEntityList ) {
            String openConversationId = dingBundleEntity.getOpenConversationId();
            JSONObject result = null;
            try {
                result = miniMemberInfoHelper.getGroupInfo(accessToken,openConversationId);
            } catch (OApiException e) {
                LOG.error("获取群信息失败",e);
                continue;
            }
            if (Objects.isNull(result)){
                LOG.info("bundleInfo is null",dingBundleEntity.getOpenConversationId());
            }
            String title = result.getString("title");
            String icon = result.getString("icon");
            String ownerUserId = result.getString("owner_staff_id");
            List<String> subAdminStaffIds = (List<String>) result.get("sub_admin_staff_ids");
            LOG.info("openConversationId:{}, bundleInfo:{}",dingBundleEntity.getOpenConversationId(),result);
            LOG.info("群主为："+ownerUserId);
            LOG.info("群管理员为："+subAdminStaffIds);
            String name = null;
            String avatar = null;
            UserEntity userEntity = userModel.getByKey(ownerUserId, corpid);
            if ( Objects.nonNull(userEntity) ) {
                name = userEntity.getName();
                avatar = userEntity.getAvatar();
            }
            dingBundleEntity.setTitle(title);
            dingBundleEntity.setIcon(icon);
            dingBundleEntity.setOwnerId(ownerUserId);
            dingBundleEntity.setName(name);
            dingBundleEntity.setAvatar(avatar);
            dingBundleModel.update(dingBundleEntity);
            if ( CollectionsUtil.isNotEmpty(subAdminStaffIds) ) {
                dingBundleUserModel.updateBatchSubAdmin(corpid,openConversationId,subAdminStaffIds);
            }
        
            Boolean hasMore = true;
            String cursor = "1";
            List<String> menberUserIds = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            while (hasMore) {
                JSONObject jsonMember = null;
                try {
                    jsonMember = miniMemberInfoHelper.getGroupMemberInfo(accessToken,openConversationId,cursor);
                } catch (OApiException e) {
                    LOG.error("获取群成员信息失败",e);
                    continue;
                }
                LOG.info("jsonMember:{}",jsonMember);
                if (Objects.isNull(jsonMember)){
                    LOG.info("jsonMember is null",dingBundleEntity.getOpenConversationId());
                }
                LOG.info("群成员信息为1："+jsonMember);
                List<String> memberList =(List<String>) jsonMember.get("member_user_ids");
                LOG.info("群成员信息为2："+memberList);
                menberUserIds.addAll(memberList);
                hasMore = jsonMember.getBoolean("has_more");
                cursor = jsonMember.getString("next_cursor");
            }
            param.clear();
            param.put("corpid",corpid);
            param.put("del",0);
            param.put("bundleId",dingBundleEntity.getId());
            List<DingBundleUserEntity> dingBundleUserEntityList = dingBundleUserModel.findEntitys(param);
            //不需要操作的用户
            List<String> noRemoveUserId = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            //需要删除的用户
            List<String> needRemoveUserId = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            //需要删除的用户
            List<Long> removeDataIdIn = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
    
            dingBundleUserEntityList.forEach(dingBundleUserEntity -> {
                String userId = dingBundleUserEntity.getUserId();
                if ( menberUserIds.contains(userId) ){
                    noRemoveUserId.add(userId);
                } else {
                    needRemoveUserId.add(userId);
                    removeDataIdIn.add(dingBundleUserEntity.getId());
                }
            });
            menberUserIds.removeAll(needRemoveUserId);
            menberUserIds.removeAll(noRemoveUserId);
            if ( CollectionsUtil.isNotEmpty(menberUserIds) ) {
                try {
                    updateBundleUser(corpid,dingBundleEntity.getId(),dingBundleEntity.getOpenConversationId(),menberUserIds,removeDataIdIn,DingBundleUserOperateEnum.ADD_MEMBER);
                } catch (Exception e) {
                    LOG.info("com.xbongbong.saas.service.impl.BundleServiceImpl.synBundleInfo#addMember is error",e);
                }
            }
            if ( CollectionsUtil.isNotEmpty(removeDataIdIn) ) {
                try {
                    updateBundleUser(corpid,dingBundleEntity.getId(),dingBundleEntity.getOpenConversationId(),needRemoveUserId,removeDataIdIn,DingBundleUserOperateEnum.DELETE_MEMBER);
                } catch (Exception e) {
                    LOG.info("com.xbongbong.saas.service.impl.BundleServiceImpl.synBundleInfo#deleteMember is error",e);
                }
            }
        }
        return new BaseVO();
    }
    /**
     * Description: 生成钉钉群的推送数据
     *
     * @param messageSaveAllDingRobotDataDTO
     * @author chenshan
     * @date 2020-10-09 17:29
     * 1.查询开通这个钉钉群的公司
     * 2.查出有几个群
     * 2.查询钉钉群的推送设置是否有开启
     * 3.轮训钉钉群的设置并生成推送数据
     *
     */
    @Override
    public void dingRobotSaveDate(MessageSaveAllDingRobotDataDTO messageSaveAllDingRobotDataDTO) throws XbbException {
        LOG.info("==============================开始生成机器人推送数据==================================");
        String oneCorpid = messageSaveAllDingRobotDataDTO.getOneCorpid();
        String alias = messageSaveAllDingRobotDataDTO.getAlias();
        String nowTimeStr = DateTimeUtil.getStringEpochSecond(DateTimeUtil.getStartOfHour(DateTimeUtil.getInt())/1000, DateTimeUtil.SDFHour_Minutes);
        String[] hourMinuteList = nowTimeStr.split(StringConstant.COLON);
        Integer hour = Integer.valueOf(hourMinuteList[0]);
        Integer minute = Integer.valueOf(hourMinuteList[1]);
        Long staticTime = DateTimeUtil.getTodayInt() + hour * TimeConstant.SECONDS_PER_HOUR + minute * TimeConstant.SECONDS_PER_MINUTE;
        Long startDate = DateTimeUtil.getTodayInt();
        Long endDate = staticTime;
        List<PaasAppEntity>  bundleAppList = null;
        Long idGet = 0L;
        Boolean hasMore = true;
        while (hasMore) {
            bundleAppList = paasAppModel.getDingBundleByAlias(idGet,oneCorpid);
            if ( CollectionsUtil.isEmpty(bundleAppList) ) {
                hasMore = false;
                continue;
            }
            idGet = bundleAppList.get(bundleAppList.size()-1).getId();
            for ( PaasAppEntity appEntity : bundleAppList ) {
                String corpid = appEntity.getCorpid();
                Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                param.put("corpid", corpid);
                param.put("type", DingBundleTypeEnum.SALES_GROUP.getCode());
                param.put("status", 1);
                param.put("del", 0);
                List<DingBundleEntity> dingBundleEntityList = dingBundleModel.findEntitys(param);
                Set<String> openConversationIdIn = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                Map<String, Long> bundleIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                dingBundleEntityList.forEach(dingBundleEntity -> {
                    openConversationIdIn.add(dingBundleEntity.getOpenConversationId());
                    bundleIdMap.put(dingBundleEntity.getOpenConversationId(), dingBundleEntity.getId());
                });
                if ( CollectionsUtil.isEmpty(openConversationIdIn) ) {
                    continue;
                }
                param.clear();
                //获取每个群的人数
                param.put("corpid", corpid);
                param.put("openConversationIdIn", openConversationIdIn);
                param.put("del", 0);
                List<DingBundleUserEntity> dingBundleUserEntityList = dingBundleUserModel.findEntitys(param);
                Map<String, Set<String>> openConversationIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                Set<String> userIdIn = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                Map<String, JSONObject> userAvatarMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                dingBundleUserEntityList.forEach(dingBundleUserEntity -> {
                    String openConversationId = dingBundleUserEntity.getOpenConversationId();
                    Set<String> userIdSet = openConversationIdMap.getOrDefault(openConversationId, new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY));
                    String userId = dingBundleUserEntity.getUserId();
                    userIdIn.add(userId);
                    userIdSet.add(userId);
                    JSONObject object = userAvatarMap.get(userId);
                    if ( Objects.isNull(object) ) {
                        object = new JSONObject();
                        object.put("userId", userId);
                        object.put("name", dingBundleUserEntity.getName());
                        object.put("avatar", dingBundleUserEntity.getAvatar());
                        userAvatarMap.put(userId, object);
                    }
                    openConversationIdMap.put(openConversationId, userIdSet);
                });
                if ( CollectionsUtil.isEmpty(userIdIn) ) {
                    continue;
                }
                param.clear();
                param.put("corpid", corpid);
                param.put("openConversationIdIn", openConversationIdIn);
                CommentUtil.addToMap(param, "alias", alias);
                param.put("aliasNotIn", Arrays.asList(DingRobotManagePushEnum.CLINCH_DEAL_CONTRACT.getAlias(), DingRobotManagePushEnum.VISITORS_TO_PLAN.getAlias()));
                param.put("del", 0);
                List<DingRobotManageEntity> dingRobotManageList = dingRobotManageModel.findEntitys(param);
                //如果现在时间不等于统计时间
                List<DingRobotManageEntity> removeRobotManageList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                LOG.info("nowTimeStr" + nowTimeStr);
                dingRobotManageList.forEach(entity -> {
                    if ( !Objects.equals(nowTimeStr, entity.getStatisticsDeadline()) || !Objects.equals(entity.getEnable(), 1) ) {
                        openConversationIdIn.remove(entity.getOpenConversationId());
                        removeRobotManageList.remove(entity);
                    }
                });
                dingRobotManageList.removeAll(removeRobotManageList);
                if ( Objects.equals(nowTimeStr, "09:00") ) {
                    getDingRobotManageList(openConversationIdIn, dingRobotManageList, bundleIdMap);
                }
                for ( DingRobotManageEntity entity : dingRobotManageList ) {
                    //保险起见，多防一道
                    if ( !Objects.equals(nowTimeStr, entity.getStatisticsDeadline()) || !Objects.equals(entity.getEnable(), 1) ) {
                        continue;
                    }
                    Set<String> userIdSet = openConversationIdMap.get(entity.getOpenConversationId());
                    String configAlias = entity.getAlias();
                    DingRobotManagePushEnum dingRobotManagePushEnum = DingRobotManagePushEnum.getByAlias(configAlias);
                    String fieldGroup = ContractEnum.getEsAttr4Keyword(ContractEnum.SIGN_PERSON);
                    String fieldSumAmount = ContractEnum.getEsAttr4Keyword(ContractEnum.AMOUNT);
                    LOG.info("推送类型==========" + JSON.toJSONString(dingRobotManagePushEnum));
                    switch (dingRobotManagePushEnum) {
                        case MOST_ORDERS:
                            //打单最多
                            TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("aggs01").field(fieldGroup);
                            termsAggregationBuilder.size(1);
                            BoolQueryBuilder filter = boolQuery()
                                    .filter(termQuery("corpid.keyword", corpid))
                                    .filter(termQuery("del", 0))
                                    .filter(termsQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.SIGN_PERSON), userIdSet))
                                    .filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())))
                                    .filter(rangeQuery(ContractEnum.ADD_TIME.getAttr()).gte(startDate).lt(endDate));
                            try {
                                JSONObject resultJsonObject = esHelper.elasticAggs4Buckets2Object(IndexTypeEnum.IDX_SAAS_CONTRACT, filter, termsAggregationBuilder);
                                JSONArray bucketsArray = resultJsonObject.getJSONArray("buckets");
                                Map<String, Integer> userCountMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                                for ( Object object : bucketsArray ) {
                                    Integer count;
                                    if ( object != null ) {
                                        JSONObject json = (JSONObject) object;
                                        String uid = json.getString("key");
                                        if ( !userIdIn.contains(uid) ) {
                                            continue;
                                        }
                                        count = json.getInteger("doc_count");
                                        userCountMap.put(uid, count);
                                    }
                                }
                                Map<String, Integer> maxOrder = SortHelp.sortMapValueInteger4KeyString(userCountMap, 1);
                                //查询一下今天是否有统计过，如果有，就直接删除掉
                                dingReportModel.deleteByRecordTime(corpid, 1, entity.getOpenConversationId(), DateTimeUtil.getTodayInt(), DateTimeUtil.getTodayEndInt(DateTimeUtil.getInt()));
                                for ( Map.Entry<String, Integer> entry : maxOrder.entrySet() ) {
                                    JSONObject userObject = userAvatarMap.get(entry.getKey());
                                    Integer number = userCountMap.getOrDefault(entry.getKey(), 0);
                                    if ( Objects.isNull(userObject) ) {
                                        continue;
                                    }
                                    DingReportEntity dingReportEntity = new DingReportEntity();
                                    dingReportEntity.setPushUrl("");
                                    dingReportEntity.setCorpid(corpid);
                                    dingReportEntity.setBundleId(entity.getBundleId());
                                    dingReportEntity.setType(1);
                                    dingReportEntity.setRecordTime(staticTime);
                                    dingReportEntity.setAvatar(userObject.getString("avatar"));
                                    dingReportEntity.setName(userObject.getString("name"));
                                    dingReportEntity.setUserId(userObject.getString("userId"));
                                    dingReportEntity.setOpenConversationId(entity.getOpenConversationId());
                                    dingReportEntity.setFinishNum(number.doubleValue());
                                    dingReportModel.insert(dingReportEntity);
                                }
                            } catch (XbbException e) {
                                LOG.error("messageServiceimpl.dingRobotSaveDate 统计打单最多出错 corpid = " + corpid);
                            }
                            break;
                        case MAX_ORDER_AMOUNT:
                            //成交金额最多
                            TermsAggregationBuilder amountTermsAggregationBuilder = esHelper.getTermsAggregationOrder4Two(1, BucketOrder.aggregation("aggs02", false), fieldGroup, fieldSumAmount, "aggs01", "aggs02");
                            BoolQueryBuilder boolQueryBuilder = boolQuery()
                                    .filter(termQuery("corpid.keyword", corpid))
                                    .filter(termQuery("del", 0))
                                    .filter(termsQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.SIGN_PERSON), userIdSet))
                                    .filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())))
                                    .filter(rangeQuery(ContractEnum.ADD_TIME.getAttr()).gte(startDate).lt(endDate));
                            try {
                                JSONObject resultJsonObject = esHelper.elasticAggs4Buckets2Object(IndexTypeEnum.IDX_SAAS_CONTRACT, boolQueryBuilder, amountTermsAggregationBuilder);
                                JSONArray bucketsArray = resultJsonObject.getJSONArray("buckets");
                                Map<String, Double> userCountMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                                for ( Object object : bucketsArray ) {
                                    if ( object != null ) {
                                        JSONObject json = (JSONObject) object;
                                        String uid = json.getString("key");
                                        if ( !userIdIn.contains(uid) ) {
                                            continue;
                                        }
                                        Double amountTotal = json.getJSONObject("aggs02").getDoubleValue("value");
                                        userCountMap.put(uid, amountTotal);
                                    }
                                }
                                Map<String, Integer> maxOrder = SortHelp.sortMapValueDouble4KeyString(userCountMap, 1);
                                //查询一下今天是否有统计过，如果有，就直接删除掉
                                dingReportModel.deleteByRecordTime(corpid, 2, entity.getOpenConversationId(), DateTimeUtil.getTodayInt(), DateTimeUtil.getTodayEndInt(DateTimeUtil.getInt()));
                                for ( Map.Entry<String, Integer> entry : maxOrder.entrySet() ) {
                                    JSONObject userObject = userAvatarMap.get(entry.getKey());
                                    Double amount = userCountMap.getOrDefault(entry.getKey(), 0.0D);
                                    if ( Objects.isNull(userObject) ) {
                                        continue;
                                    }
                                    DingReportEntity dingReportEntity = new DingReportEntity();
                            
                                    dingReportEntity.setCorpid(corpid);
                                    dingReportEntity.setPushUrl("");
                                    dingReportEntity.setBundleId(entity.getBundleId());
                                    dingReportEntity.setType(2);
                                    dingReportEntity.setRecordTime(staticTime);
                                    dingReportEntity.setAvatar(userObject.getString("avatar"));
                                    dingReportEntity.setName(userObject.getString("name"));
                                    dingReportEntity.setUserId(userObject.getString("userId"));
                                    dingReportEntity.setOpenConversationId(entity.getOpenConversationId());
                                    dingReportEntity.setFinishNum(amount);
                                    dingReportModel.insert(dingReportEntity);
                                }
                            } catch (XbbException e) {
                                LOG.error("messageServiceimpl.dingRobotSaveDate 统计成交金额最多出错 corpid = " + corpid);
                            }
                            break;
                        case PERFORMANCE_RANKING:
                            //业绩排行
                            TermsAggregationBuilder rankTermsAggregationBuilder = esHelper.getTermsAggregation4Two(fieldGroup, fieldSumAmount, "aggs01", "aggs02");
                            BoolQueryBuilder rankBoolQueryBuilder = boolQuery()
                                    .filter(termQuery("corpid.keyword", corpid))
                                    .filter(termQuery("del", 0))
                                    .filter(termsQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.SIGN_PERSON), userIdSet))
                                    .filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())))
                                    .filter(rangeQuery(ContractEnum.ADD_TIME.getAttr()).gte(startDate).lt(endDate));
                            try {
                                JSONObject resultJsonObject = esHelper.elasticAggs4Buckets2Object(IndexTypeEnum.IDX_SAAS_CONTRACT, rankBoolQueryBuilder, rankTermsAggregationBuilder);
                                JSONArray bucketsArray = resultJsonObject.getJSONArray("buckets");
                                Map<String, Double> userAmountMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                                for ( Object object : bucketsArray ) {
                                    if ( object != null ) {
                                        JSONObject json = (JSONObject) object;
                                        String uid = json.getString("key");
                                        if ( !userIdIn.contains(uid) ) {
                                            continue;
                                        }
                                        Double amountTotal = json.getJSONObject("aggs02").getDoubleValue("value");
                                        userAmountMap.put(uid, amountTotal);
                                    }
                                }
                                Map<String, Integer> maxOrder = SortHelp.sortMapValueDouble4KeyString(userAmountMap, userAmountMap.size());
                                List<DingBundleRankEntity> rankList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                                Integer sort = 0;
                                dingBundleRankModel.deleteByRecordTime(corpid, entity.getOpenConversationId(), DateTimeUtil.getTodayInt(), DateTimeUtil.getTodayEndInt(DateTimeUtil.getInt()));
                                for ( Map.Entry<String, Integer> entry : maxOrder.entrySet() ) {
                                    JSONObject userObject = userAvatarMap.get(entry.getKey());
                                    Double amount = userAmountMap.get(entry.getKey());
                                    if ( Objects.isNull(userObject) ) {
                                        continue;
                                    }
                                    DingBundleRankEntity dingBundleRankEntity = new DingBundleRankEntity();
                                    sort++;
                                    dingBundleRankEntity.setCorpid(corpid);
                                    dingBundleRankEntity.setPushUrl("");
                                    dingBundleRankEntity.setBundleId(entity.getBundleId());
                                    dingBundleRankEntity.setRankTime(DateTimeUtil.getTodayInt());
                                    dingBundleRankEntity.setAvatar(userObject.getString("avatar"));
                                    dingBundleRankEntity.setName(userObject.getString("name"));
                                    dingBundleRankEntity.setUserId(userObject.getString("userId"));
                                    dingBundleRankEntity.setOpenConversationId(entity.getOpenConversationId());
                                    dingBundleRankEntity.setSort(sort);
                                    dingBundleRankEntity.setAmount(amount);
                                    rankList.add(dingBundleRankEntity);
                                }
                                if ( CollectionsUtil.isNotEmpty(rankList) ) {
                                    dingBundleRankModel.insertBatch(rankList);
                                }
                            } catch (XbbException e) {
                                LOG.error("messageServiceimpl.dingRobotSaveDate 统计业绩排行出错 corpid = " + corpid);
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
        }
        LOG.info("==============================结束生成机器人推送数据==================================");
    }
    
    /**
     * Description: 推送钉钉群的数据
     *
     * @param messageSaveAllDingRobotDataDTO
     * @author chenshan
     * @date 2020-10-09 17:29
     * 1.查询开通这个钉钉群的公司
     *
     */
    @Override
    public void dingRobotDatePush(MessageSaveAllDingRobotDataDTO messageSaveAllDingRobotDataDTO) throws XbbException {
        LOG.info("==============================开始推送机器人数据==================================");
        String oneCorpid = messageSaveAllDingRobotDataDTO.getOneCorpid();
        String alias = messageSaveAllDingRobotDataDTO.getAlias();
        Long pushTime = (DateTimeUtil.getStartOfHour(DateTimeUtil.getInt()) / 1000) + 60 * 5;
        String pushTimeStr = DateTimeUtil.getStringEpochSecond(pushTime, DateTimeUtil.SDFHour_Minutes);
        List<PaasAppEntity>  bundleAppList = null;
        Long idGet = 0L;
        Boolean hasMore = true;
        while (hasMore) {
            bundleAppList = paasAppModel.getDingBundleByAlias(idGet,oneCorpid);
            if ( CollectionsUtil.isEmpty(bundleAppList) ) {
                hasMore = false;
                continue;
            }
            idGet = bundleAppList.get(bundleAppList.size()-1).getId();
            for ( PaasAppEntity appEntity : bundleAppList ) {
                String corpid = appEntity.getCorpid();
                Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                param.put("corpid", corpid);
                param.put("type", DingBundleTypeEnum.SALES_GROUP.getCode());
                param.put("status", 1);
                param.put("del", 0);
                List<DingBundleEntity> dingBundleEntityList = dingBundleModel.findEntitys(param);
                Set<String> openConversationIdIn = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                Map<String, Long> bundleIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                dingBundleEntityList.forEach(dingBundleEntity -> {
                    openConversationIdIn.add(dingBundleEntity.getOpenConversationId());
                    bundleIdMap.put(dingBundleEntity.getOpenConversationId(), dingBundleEntity.getId());
                });
                if ( CollectionsUtil.isEmpty(openConversationIdIn) ) {
                    continue;
                }
                param.clear();
                param.put("corpid", corpid);
                param.put("openConversationIdIn", openConversationIdIn);
                CommentUtil.addToMap(param, "alias", alias);
                param.put("aliasNotIn", Arrays.asList(DingRobotManagePushEnum.CLINCH_DEAL_CONTRACT.getAlias(), DingRobotManagePushEnum.VISITORS_TO_PLAN.getAlias()));
                param.put("del", 0);
                param.put("pushTime", pushTimeStr);
                List<DingRobotManageEntity> dingRobotManageList = dingRobotManageModel.findEntitys(param);
                //如果现在时间不等于统计时间
                List<DingRobotManageEntity> removeRobotManageList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                LOG.info("pushTimeStr" + pushTimeStr);
                dingRobotManageList.forEach(entity -> {
                    if ( !Objects.equals(pushTimeStr, entity.getStatisticsDeadline()) || !Objects.equals(entity.getEnable(), 1) ) {
                        openConversationIdIn.remove(entity.getOpenConversationId());
                        removeRobotManageList.remove(entity);
                    }
                });
                dingRobotManageList.removeAll(removeRobotManageList);
                if ( Objects.equals(pushTimeStr, "09:05") ) {
                    getDingRobotManageList(openConversationIdIn, dingRobotManageList, bundleIdMap);
                }
                for ( DingRobotManageEntity entity : dingRobotManageList ) {
                    //保险起见，多防一道
                    if ( !Objects.equals(pushTimeStr, entity.getPushTime()) || !Objects.equals(entity.getEnable(), 1) ) {
                        continue;
                    }
                    String configAlias = entity.getAlias();
                    Long startPushTime = DateTimeUtil.getTodayInt();
                    DingRobotManagePushEnum dingRobotManagePushEnum = DingRobotManagePushEnum.getByAlias(configAlias);
                    String messageUrl = proBaseConfig.getPushFrontUrl() + "index.html?corpid=" + corpid + "&appid=" + Env.DING_XBB_APP_ID + "&dd_nav_bgcolor=ffff943e#";
                    String pcMessageUrl = "dingtalk://dingtalkclient/page/link?url=";
                    switch (dingRobotManagePushEnum) {
                        case MOST_ORDERS:
                            param.clear();
                            param.put("openConversationId", entity.getOpenConversationId());
                            param.put("corpid", corpid);
                            param.put("isPush", 0);
                            param.put("addStartTime", startPushTime);
                            param.put("addEndTime", pushTime);
                            param.put("type", 1);
                            param.put("del", 0);
                            List<DingReportEntity> reportEntityList = dingReportModel.findEntitys(param);
                            for ( DingReportEntity report : reportEntityList ) {
                                String cid = URLEncodeUtils.encodeURL(report.getOpenConversationId());
                                messageUrl += String.format(DingtalkPageUrlEnum.BUNDLE_GOOD_NEWS_DETAIL.getUrl(), report.getCorpid(), report.getId(), cid);
                                pcMessageUrl += URLEncodeUtils.encodeURL(messageUrl) + "&pc_slide=true";
                                String imgUrl = null;
                                try {
                                    imgUrl = createImageHelper.xhtmlToImage(corpid, dingRobotManagePushEnum, null, report.getName(), report.getAvatar(), report.getFinishNum(), report.getAddTime());
                                } catch (IOException e) {
                                    LOG.error("打单王者图片生成错误", e);
                                    continue;
                                }
                                String text = "![screenshot](" + imgUrl + ")";
                                groupRobotHelper.sendRobotMsg(DingBundleRobotMsgKeyEnum.ACTIONCARD_1, corpid, report.getName(), report.getId(), Arrays.asList(report.getOpenConversationId()), text, pcMessageUrl);
                                report.setIsPush(1);
                                report.setPushUrl(pcMessageUrl);
                                report.setPushTime(DateTimeUtil.getInt());
                            }
                            if ( !reportEntityList.isEmpty() ) {
                                dingReportModel.updateBatch(reportEntityList, corpid);
                            }
                            break;
                        case MAX_ORDER_AMOUNT:
                            param.clear();
                            param.put("corpid", corpid);
                            param.put("openConversationId", entity.getOpenConversationId());
                            param.put("isPush", 0);
                            param.put("addStartTime", startPushTime);
                            param.put("addEndTime", pushTime);
                            param.put("type", 2);
                            param.put("del", 0);
                            List<DingReportEntity> reportList = dingReportModel.findEntitys(param);
                            for ( DingReportEntity report : reportList ) {
                                String cid = URLEncodeUtils.encodeURL(report.getOpenConversationId());
                                messageUrl += String.format(DingtalkPageUrlEnum.BUNDLE_GOOD_NEWS_DETAIL.getUrl(), report.getCorpid(), report.getId(), cid);
                                pcMessageUrl += URLEncodeUtils.encodeURL(messageUrl) + "&pc_slide=true";
                                String imgUrl = null;
                                try {
                                    imgUrl = createImageHelper.xhtmlToImage(corpid, dingRobotManagePushEnum, null, report.getName(), report.getAvatar(), report.getFinishNum(), report.getAddTime());
                                } catch (IOException e) {
                                    LOG.error("成交王者图片生成错误", e);
                                    continue;
                                }
                                String text = "![screenshot](" + imgUrl + ")";
                                groupRobotHelper.sendRobotMsg(DingBundleRobotMsgKeyEnum.ACTIONCARD_1, corpid, report.getName(), report.getId(), Arrays.asList(report.getOpenConversationId()), text, pcMessageUrl);
                                report.setIsPush(1);
                                report.setPushUrl(messageUrl);
                                report.setPushTime(DateTimeUtil.getInt());
                            }
                            if ( !reportList.isEmpty() ) {
                                dingReportModel.updateBatch(reportList, corpid);
                            }
                            break;
                        case PERFORMANCE_RANKING:
                            param.clear();
                            param.put("corpid", corpid);
                            param.put("isPush", 0);
                            param.put("openConversationId", entity.getOpenConversationId());
                            param.put("rankTimeStart", startPushTime);
                            param.put("rankTimeEnd", pushTime);
                            param.put("del", 0);
                            param.put("orderByStr", "sort asc");
                            param.put("start", 0);
                            param.put("pageNum", 5);
                            LOG.info("查询业绩排行榜数据1：" + JSON.toJSONString(param));
                            List<DingBundleRankEntity> dingBundleRankList = dingBundleRankModel.findEntitys(param);
                            LOG.info("查询业绩排行榜数据2：" + JSON.toJSONString(dingBundleRankList));
                            List<Long> dataIdIn = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                            if ( CollectionsUtil.isEmpty(dingBundleRankList) ) {
                                continue;
                            }
                            for ( DingBundleRankEntity dingBundleRankEntity : dingBundleRankList ) {
                                dataIdIn.add(dingBundleRankEntity.getId());
                            }
                            String imgUrl = null;
                            try {
                                imgUrl = createImageHelper.xhtmlToImage(corpid, dingRobotManagePushEnum, dingBundleRankList, null, null, null, dingBundleRankList.get(0).getAddTime());
                            } catch (IOException e) {
                                LOG.error("业绩排行图片生成错误", e);
                                continue;
                            }
                            String text = "![screenshot](" + imgUrl + ")";
                            String cid = URLEncodeUtils.encodeURL(entity.getOpenConversationId());
                            messageUrl += String.format(DingtalkPageUrlEnum.BUNDLE_PERFORMANCE_DETAIL.getUrl(), entity.getCorpid(), DateTimeUtil.getTodayInt(dingBundleRankList.get(0).getRankTime()), DateTimeUtil.getTodayEndInt(dingBundleRankList.get(0).getRankTime()), DateTimeUtil.getDateStringEpochSecond(dingBundleRankList.get(0).getRankTime()) + "业绩排行", cid);
                            pcMessageUrl += URLEncodeUtils.encodeURL(messageUrl) + "&pc_slide=true";
                            groupRobotHelper.sendRobotMsg(DingBundleRobotMsgKeyEnum.ACTIONCARD_1, corpid, null, null, Arrays.asList(entity.getOpenConversationId()), text, pcMessageUrl);
                            dingBundleRankModel.updateBatch(dataIdIn, entity.getCorpid(), 1, pcMessageUrl);
                            break;
                        default:
                            break;
                    }
                }
            }
        }
        LOG.info("==============================结束推送机器人数据==================================");
    }
    
    private List<DingRobotManageEntity> getDingRobotManageList(Set<String> openConversationIdIn, List<DingRobotManageEntity> dingRobotManageList,Map<String,Long> bundleIdMap) {
        if ( CollectionsUtil.isEmpty(dingRobotManageList) ){
            dingRobotManageList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        }
        Map<String, Set<String>> openConversationIdAliasIn = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        openConversationIdIn.forEach(openConversationId->{
            openConversationIdAliasIn.put(openConversationId,new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY));
        });
        dingRobotManageList.forEach(dingRobotManageEntity -> {
            String openConversationId = dingRobotManageEntity.getOpenConversationId();
            String dingAlias = dingRobotManageEntity.getAlias();
            Set<String> aliasList = openConversationIdAliasIn.getOrDefault(openConversationId,new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY));
            aliasList.add(dingAlias);
            openConversationIdAliasIn.put(openConversationId,aliasList);
        });
        for ( Map.Entry<String,Set<String>> entry:  openConversationIdAliasIn.entrySet()) {
            Set<String> aliasList =entry.getValue();
            String openConversationId = entry.getKey();
            Long bundleId = bundleIdMap.get(openConversationId);
            if ( !aliasList.contains(DingRobotManagePushEnum.MOST_ORDERS.getAlias()) ) {
                DingRobotManageEntity dingRobotManageEntity = new DingRobotManageEntity(DingRobotManagePushEnum.MOST_ORDERS,openConversationId,bundleId);
                dingRobotManageList.add(dingRobotManageEntity);
            }
            if ( !aliasList.contains(DingRobotManagePushEnum.MAX_ORDER_AMOUNT.getAlias()) ) {
                DingRobotManageEntity dingRobotManageEntity = new DingRobotManageEntity(DingRobotManagePushEnum.MAX_ORDER_AMOUNT,openConversationId,bundleId);
                dingRobotManageList.add(dingRobotManageEntity);
            }
            if ( !aliasList.contains(DingRobotManagePushEnum.PERFORMANCE_RANKING.getAlias()) ) {
                DingRobotManageEntity dingRobotManageEntity = new DingRobotManageEntity(DingRobotManagePushEnum.PERFORMANCE_RANKING,openConversationId,bundleId);
                dingRobotManageList.add(dingRobotManageEntity);
            }
        }
        return dingRobotManageList;
    }
}
